//
//  OauthViewModel.swift
//  SinaBlog
//
//  Created by 有何不可 on 16/1/2.
//  Copyright © 2016年 有何不可. All rights reserved.
//

import UIKit
import AFNetworking

class OauthViewModel: NSObject {
    
    static let sharedInstance = OauthViewModel()
    
    var model: OauthModel?
    // 为了 实现MVVM的设计模式,不让控制器与模型有直接访问,则这样设置个属性;
    var access_token: String {
        
        return model?.access_token ?? ""
    }
    
    var isLogin: Bool {
        
        
        return access_token == "" ? false: true
    }
    
    override init() {
      
        model = OauthModel.getUserInfo()
    }
    
    // MARK: -- 获取token
    func getToken(str: String, success: () -> (), fail: (NSError) -> ()) {
        
        let manager = AFHTTPSessionManager()
        
        manager.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        /*
        client_id	true	string	申请应用时分配的AppKey。
        client_secret	true	string	申请应用时分配的AppSecret。
        grant_type	true	string	请求的类型，填写authorization_code
        
        grant_type为authorization_code时
        
        code	true	string	调用authorize获得的code值。
        redirect_uri	true	string	回调地址，需需与注册应用里的回调地址一致。
        
        */
        
        let dict = [
            "client_id": app_Key,
            "client_secret": app_Secret,
            "grant_type": "authorization_code",
            "code": str,
            "redirect_uri": "http://www.baidu.com"
        ]
        
        
        manager.POST("https://api.weibo.com/oauth2/access_token", parameters: dict, success: { (_, responser) -> Void in
            /*
            access_token" = "2.00euKSgCAGnlAD75bb86223fO_hgHC";
            "expires_in" = 157679999;
            "remind_in" = 157679999;
            uid = 2457203632;
            */
            
            let dict = responser as? [String: AnyObject]
            
            if let OKdict = dict {
                
                let account = OauthModel(dict: OKdict)
                
//                print(account)
                
                self.getUserInfo(account, success: success, fail: fail)
            }
            
            }) { (_, error) -> Void in
                print(error)
        }
    }
    
    private func getUserInfo(account: OauthModel, success: () -> (), fail: (error: NSError) -> ()) {
        
        let manager = AFHTTPSessionManager()
        
        /*
        source	false	string	采用OAuth授权方式不需要此参数，其他授权方式为必填参数，数值为应用的AppKey。
        access_token	false	string	采用OAuth授权方式为必填参数，其他授权方式不需要此参数，OAuth授权后获得。
        uid	false	int64	需要查询的用户ID。
        screen_name	false	string	需要查询的用户昵称。
        
        参数uid与screen_name二者必选其一，且只能选其一
        */
        
        let dict = [
            "access_token": account.access_token!,
            "uid": account.uid!
        ]
        
        manager.GET("https://api.weibo.com/2/users/show.json", parameters: dict, success: { (_, responser) -> Void in
            
            if let userInfo = responser as? [String: AnyObject] {
                
                account.screen_name = userInfo["screen_name"] as? String
                account.profile_image_url = userInfo["profile_image_url"] as? String
                //                print(person)
                
                account.saveIn()
                
                self.model = account
                
                success()
            }
            }) { (_, error) -> Void in
                
                print(error)
                
                fail(error: error)
        }
    }
    
}
